package main

import (
	"io/ioutil"
	"publiclib/cache"
	"publiclib/config"
	"publiclib/logs"
	"runtime"

	"generatorserver/internal/gcs"

	log "github.com/sirupsen/logrus"
	"gopkg.in/yaml.v2"
)

var (
	confFile    string
	featureFile string
)

// loadConfFromFile 从配置文件加载配置信息
func loadConfFromFile(fs string, po interface{}) error {
	data, err := ioutil.ReadFile(fs)
	if err == nil {
		if err = yaml.Unmarshal(data, po); err != nil {
			return err
		}
	}
	return nil
}

// DoInitLibs 初始基库
func DoInitLibs() {
	// 初始一份SP, sp不能用在用户层的处理
	sp := gcs.Sp()
	config.SetSecretProcess(sp)
	//
	cfg := config.Instance()
	if err := loadConfFromFile(confFile, cfg); err != nil {
		panic(err)
	}
	cfg.DoOnceDataFix()
	// 初始Cache, 默认5秒, db3
	cache.Init(cfg.Redis.GetURI(), cfg.Redis.Pass, 5000, 1)

	// 初始log的输出口
	if cfg.Syslog.Enable && runtime.GOOS != "windows" {
		log.Infof("redirect log to %s:%d", cfg.Syslog.Host, cfg.Syslog.Port)
		if err := logs.EnableSyslog(cfg.Syslog.Host, cfg.Syslog.Port, gcs.AppName); err != nil {
			log.Panic(err)
		}
	} else {
		log.SetFormatter(&log.TextFormatter{FullTimestamp: true, TimestampFormat: "20060102 15:04:05"})
	}
}
